package main

import (
	"encoding/json"
	"fmt"
	"log"
	"reflect"
)

/**********************
***********  解析json串
***********************/

func parseJson(jsonStr string, target interface{}) error {
	var data map[string]interface{}
	if err := json.Unmarshal([]byte(jsonStr), &data); err != nil {
		log.Fatal(err)
		return err
	}
	//获取实际的对象
	v := reflect.ValueOf(target).Elem()
	//遍历data ,填充到v中
	for key, value := range data {
		field := v.FieldByName(key)
		if field.IsValid() && field.CanSet() {
			field.Set(reflect.ValueOf(value))
		}
	}
	return nil
}

type Config struct {
	Port int
	Host string
}

func main() {
	jsonStr := `{"Port": 8080, "Host": "localhost"}`
	var config Config
	parseJson(jsonStr, &config)
	fmt.Println(config) // 输出: {8080 localhost}
}
